package com.edgclub.edg.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.edgclub.edg.Constant;
import com.edgclub.edg.GuZhiApplication;
import com.edgclub.edg.R;
import com.edgclub.edg.adapter.UserPhotoAdapter;
import com.edgclub.edg.adapter.adapteruitls.MyItemClickListener;
import com.edgclub.edg.api.ApiConfig;
import com.edgclub.edg.api.ResultCode;
import com.edgclub.edg.api.UploadApi;
import com.edgclub.edg.api.UserApi;
import com.edgclub.edg.api.param.UserParam;
import com.edgclub.edg.http.VolleyListener;
import com.edgclub.edg.http.async.AsyncHttpResponseHandler;
import com.edgclub.edg.model.PostsAlbum;
import com.edgclub.edg.model.User;
import com.edgclub.edg.model.result.UserPostsImage;
import com.edgclub.edg.uc.ExitDialog;
import com.edgclub.edg.utils.util.BitmapUtility;
import com.edgclub.edg.utils.util.JSONHelper;
import com.edgclub.edg.utils.util.JsonUtil;
import com.edgclub.edg.utils.util.StringUtils;
import com.edgclub.edg.utils.util.UserPrefUtils;
import com.jcodecraeer.xrecyclerview.XRecyclerView;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import me.nereo.multi_image_selector.bean.Image;

/**
 * Created by Administrator on 2016/6/15.
 */
public class UserInfoOtherPhotoActivity extends GzBaseTooolBarActivity implements View.OnClickListener , VolleyListener{
    private XRecyclerView recyclerView;

    private int currPage = 1;
    private int pageSize = 21;
    private UserApi userApi;
    private UserPrefUtils userPrefUtils;
    private User toUser;
    private List<PostsAlbum> imageList=new ArrayList<>();
    private boolean load = false;
    private UserPhotoAdapter adapter;
    private boolean isfrist=true;
    private String del_albumIds="";
    private boolean ismy;
    private UploadApi uploadApi;
    private ArrayList<PostsAlbum> uploadPhoto=new ArrayList<>();
    private int delIndex=-1;
    private TextView text_empty;
    private ImageView imageView_empty;
    private LinearLayout layout_empty;
    @Override
    public int getContentView() {
        return R.layout.fagment_user_image;
    }

    @Override
    public void setTitleBarView() {
        setCustomActionBar();
        toUser= (User) getIntent().getSerializableExtra("user");
        if (null==toUser)toUser=new User();
        if(toUser.getId().equals(GuZhiApplication.getInstance().getUserId()))
            ismy=true;
        else
            ismy=false;
        userPrefUtils=new UserPrefUtils(this);
        if(toUser.getId().equals(userPrefUtils.getUser().getId())){
            right_layout.setVisibility(View.VISIBLE);
            right_layout.setOnClickListener(this);
            right_text.setText("编辑");
        }
        title.setText("相册");
        main_back.setOnClickListener(this);

    }

    @Override
    public void initView() {
        uploadApi = new UploadApi(this);
        userApi=new UserApi(this);
        adapter=new UserPhotoAdapter(this,ismy);
        recyclerView = (XRecyclerView) findViewById(R.id.recyclerview);
        GridLayoutManager layoutManager = new GridLayoutManager(this,3);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        layout_empty= (LinearLayout) findViewById(R.id.layout_empty);;
        text_empty= (TextView) findViewById(R.id.text_empty);;
        imageView_empty = (ImageView) findViewById(R.id.imageView_empty);
        imageView_empty.setVisibility(View.VISIBLE);
        imageView_empty.setImageResource(R.drawable.nomess);
        text_empty.setText("还没有相关内容哦");


        recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                currPage = 1;
                getUserImage(currPage);
            }

            @Override
            public void onLoadMore() {
                getUserImage(currPage);
            }
        });


    }

    @Override
    public void initData() {
        getUserImage(currPage);
        if(ismy)
        imageList.add(0,new PostsAlbum());
        adapter.setDatas(imageList);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new MyItemClickListener() {
            @Override
            public void onItemClick(View view, int postion) {
                if(postion==0&&ismy ){
                    Intent intent2 = new Intent(UserInfoOtherPhotoActivity.this, MultiImageSelectorActivity.class);
                    intent2.putExtra("selectType",0);
                    // 是否显示拍摄图片
                    intent2.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
                    // 最大可选择图片数量
                    intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 9);
                    // 选择模式
                    intent2.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_MULTI);
                    startActivityForResult(intent2, Constant.IMAGE_RESULT);
                }else{
                    Intent intent = new Intent(UserInfoOtherPhotoActivity.this,
                            ImageViewPagerActivity.class);
                    intent.putExtra("urls", (Serializable) imageList);
                    intent.putExtra("position", postion);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                    overridePendingTransition(R.anim.head_in, R.anim.head_out);
                }
            }
        });
        adapter.setDelListener(new UserPhotoAdapter.delListener() {
            @Override
            public void deletePhoto(int position,String albumId) {
                if("".equals(del_albumIds))
                    del_albumIds+=albumId;
                else
                    del_albumIds+=","+albumId;
                delIndex=position;
                delPhoto();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_back:
                if(!"".equals(del_albumIds)) {
                    blackDialog();
                }else{
                    finish();
                }
                break;
            case R.id.right_layout:
                if("编辑".equals(right_text.getText()+"")) {
                    adapter.setEditor(true);
                    right_text.setText("完成");
                }else{
                    adapter.setEditor(false);
                    right_text.setText("编辑");
                }
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Constant.IMAGE_RESULT) {
                List<Image>imageList= (List<Image>) data.getSerializableExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                if(null!=imageList&&imageList.size()>0){
                    uploadPhoto.clear();
                    for(Image image:imageList){
                        PostsAlbum postsAlbum=new PostsAlbum();
                        postsAlbum.setThumbnail(image.path);
                        postsAlbum.setUserId(GuZhiApplication.getInstance().getUserId());
                        postsAlbum.setUploadstate(true);
                        postsAlbum.setOri(image.isOri);
                        uploadPhoto.add(postsAlbum);
                    }
                    upload(0);
                    showDialog("正在上传"+uploadPhoto.size()+"张，"+"请稍后...",true);
                }
            }
        }
    }
    private void blackDialog(){
        final ExitDialog dialog=ExitDialog.create(this);
        dialog.setTitle("是否放弃此次编辑？");
        dialog.setExitText("继续编辑");
        dialog.setCancleText("放弃");
        dialog.setSubmitListener(new ExitDialog.SubmitClickListener() {
            @Override
            public void submitClick() {
                dialog.dismiss();
            }
        });
        dialog.setCancelListener(new ExitDialog.CancelClickListener() {
            @Override
            public void cancelClick() {
                finish();
            }
        });
        dialog.show();
    }
    // 默认点回退键，会退出Activity，需监听按键操作，使回退在WebView内发生
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        try {
            if (keyCode == KeyEvent.KEYCODE_BACK) {

            }
        } catch (Exception e) {
            // TODO: handle exception
        }

        return super.onKeyDown(keyCode, event);
    }
    private void getUserImage(int page){
        if(load)
            return;
        UserParam userParam=new UserParam();
        userParam.setUserId(userPrefUtils.getUser().getId());
        userParam.setToUserId(toUser.getId());
        userParam.setPage(page+"");
        userParam.setPageSize(pageSize+"");
        userApi.getOtherPhoto(userParam,this);
    }

    private void delPhoto(){
        UserParam userParam=new UserParam();
        userParam.setUserId(userPrefUtils.getUser().getId());
        userParam.setAlbumIds(del_albumIds);
        userApi.getDelImage(userParam,this);
    }


    @Override
    public void onStart(String tag) {
        load =true;
        if(isfrist||tag.equals(ApiConfig.APIURL.URL_USER_DELIMAGE))
        showDialog("正在请求...",false);
    }

    @Override
    public void onSuccess(String response, String tag) {
        dismissDialog();
        load = false;
        isfrist = false;
        recyclerView.refreshComplete();
        recyclerView.loadMoreComplete();
        if (JSONHelper.isSuccess(response)) {
            if (tag.equals(ApiConfig.APIURL.URL_USER_PHOTO)) {

                UserPostsImage userImage = JsonUtil.getMode(response,
                        UserPostsImage.class);
                if (null != userImage && null != userImage.getData() && userImage.getData().getAlbums().size() > 0) {
                    if (currPage == 1) {
                        imageList.clear();
                        if(ismy)
                        imageList.add(0,new PostsAlbum());
                    }
                    currPage++;
                    imageList.addAll(userImage.getData().getAlbums());
                    adapter.notifyDataSetChanged();
                }else{
                    if(currPage!=1){
                        recyclerView.noMoreLoading();
                    }

                }
                if (!"".equals(imageList)&&imageList.size()>0){
                    layout_empty.setVisibility(View.GONE);
                    recyclerView.setPullRefreshEnabled(true);
                }
                else {
                    layout_empty.setVisibility(View.VISIBLE);
                    recyclerView.setPullRefreshEnabled(false);
                }
            } else if (tag.equals(ApiConfig.APIURL.URL_USER_DELIMAGE)) {
                del_albumIds="";
                if(-1!=delIndex)
                imageList.remove(delIndex);
                adapter.notifyDataSetChanged();
                delIndex=-1;
                StringUtils.postToast(UserInfoOtherPhotoActivity.this,"操作成功");
            }
        }else{
            StringUtils.postToast(UserInfoOtherPhotoActivity.this,"操作失败，请重试");
        }
    }

    @Override
    public void onFaile(VolleyError volleyError, String tag) {
        load =false;
        isfrist=false;
        dismissDialog();
        recyclerView.refreshComplete();
        recyclerView.loadMoreComplete();
        ResultCode.toastVolleyError(this, volleyError);
    }

    public void upload(final int num) {
        if (uploadPhoto != null && uploadPhoto.size() > num) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Looper.prepare();
                    setnum(num);
                    Looper.loop();
                }
            }).start();
        }
    }
    private void setnum(int i) {
        if (uploadPhoto != null && uploadPhoto.size() > i) {
                PostsAlbum info = uploadPhoto.get(i);
                if(info.isUploadstate()){
                    try {
                        String pic0 = info.getThumbnail();
                        String userImageFileName = Constant.TOPICIMAGEPATH
                                + pic0.hashCode();
                        if (pic0.endsWith("png")&&info.isOri()) {
                            BitmapUtility.compressPNGFromBitmap(pic0, userImageFileName,300);
                        } else if ((pic0.endsWith("jpg") || pic0.endsWith("jpeg"))&&info.isOri() ){
                            BitmapUtility.compressImage(pic0, userImageFileName);
                        } else {
                            if(pic0.endsWith("png")){
                                BitmapUtility.compressPNGFromBitmap(pic0, userImageFileName,500);
                            }else{
                                BitmapUtility.compressImage80(pic0,userImageFileName);
                            }
//                            userImageFileName = pic0;
                        }
//                        showDialog("正在上传 "+(i+1)+"/"+uploadPhoto.size()+",请稍后... ",true);
//                        setToastext("正在上传 "+(i+1)+"/"+uploadPhoto.size()+",请稍后... ");
                        uploadApi.beginUploadUserImage( info.getUserId(),  String.valueOf(i),new File(
                                userImageFileName),new UploadUserImageHandler(info,i,uploadPhoto.size()));

                    } catch (Exception e) {
                        if(i==uploadPhoto.size()-1)
                            e.printStackTrace();
                    }
                }
        }
    }
    /**
     * 上传相册回调
     */
    public class UploadUserImageHandler extends AsyncHttpResponseHandler {

        private PostsAlbum info;
        private int total;
        private int index;
        public UploadUserImageHandler(PostsAlbum info,int index,int total) {
            this.info = info;
            this.total=total;
            this.index=index+1;
        }

        @Override
        public void onStart() {

        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            if(index==total)
                dismissDialog();
            try {
                String recString=new String(responseBody ,"UTF-8");
                Log.d("recString",recString);
                if (JSONHelper.isSuccess(recString)) {
                    upload(index);
                    String userImageFileName = Constant.TOPICIMAGEPATH
                            + info.getThumbnail().hashCode();
                    File file = new File(userImageFileName);
                    if (file.exists()) {
                        file.delete();
                    }
                    info.setUploadstate(true);

                    Message message = new Message();
                    message.what = 0;
                    message.obj = info;
                    handler.sendMessage(message);
//                    imageList.add(1,info);
//                    adapter.notifyDataSetChanged();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            if(index==total)
                dismissDialog();
        }
    }

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what == 0){
                PostsAlbum album = (PostsAlbum) msg.obj;
                imageList.add(1,album);
                adapter.notifyDataSetChanged();
            }
        }
    };
}
